package com.agrimall.servlet;

import com.agrimall.entity.User;
import com.agrimall.service.UserService;
import com.agrimall.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 统一注册Servlet - 处理客户端用户和商户的注册
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/register.jsp").forward(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userTypeStr = request.getParameter("userType");
        
        if (username == null || password == null || userTypeStr == null) {
            request.setAttribute("error", "请填写完整信息");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;
        }
        
        try {
            Integer userType = Integer.parseInt(userTypeStr);
            
            // 不允许注册管理员账号
            if (userType == 2) {
                request.setAttribute("error", "管理员账号不能通过注册创建");
                request.getRequestDispatcher("/register.jsp").forward(request, response);
                return;
            }
            
            User user = new User();
            user.setUsername(username.trim());
            user.setPassword(password);
            user.setRealName(request.getParameter("realName"));
            user.setPhone(request.getParameter("phone"));
            user.setEmail(request.getParameter("email"));
            user.setAddress(request.getParameter("address"));
            user.setUserType(userType);
            user.setStatus(1); // 默认启用
            
            boolean success = userService.register(user);
            if (success) {
                request.setAttribute("success", "注册成功，请登录");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            } else {
                request.setAttribute("error", "注册失败，用户名可能已存在");
                request.getRequestDispatcher("/register.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "注册失败：" + e.getMessage());
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        }
    }
}
















